package net.mihome.app.ui;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.easemob.EMConnectionListener;
import com.easemob.EMError;
import com.easemob.chat.CmdMessageBody;
import com.easemob.chat.EMChat;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMContactListener;
import com.easemob.chat.EMContactManager;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMGroup;
import com.easemob.chat.EMGroupManager;
import com.easemob.chat.EMMessage;
import com.easemob.chat.EMNotifier;
import com.easemob.chat.GroupChangeListener;
import com.easemob.chat.TextMessageBody;
import com.easemob.chatuidemo.Constant;
import com.easemob.chatuidemo.activity.ChatActivity;
import com.easemob.chatuidemo.activity.ContactlistFragment;
import com.easemob.chatuidemo.activity.GroupsActivity;
import com.easemob.chatuidemo.activity.LinliquanFragment;
import com.easemob.chatuidemo.db.InviteMessgeDao;
import com.easemob.chatuidemo.db.UserDao;
import com.easemob.chatuidemo.domain.InviteMessage;
import com.easemob.chatuidemo.utils.CommonUtils;
import com.easemob.util.EMLog;
import com.easemob.util.HanziToPinyin;
import com.easemob.util.NetUtils;
import com.loopj.android.http.RequestParams;

import net.mihome.app.AppContext;
import net.mihome.app.AppException;
import net.mihome.app.AppManager;
import net.mihome.app.R;
import net.mihome.app.adapter.MifuwuFragmentAdapter;
import net.mihome.app.adapter.MyFragmentAdapter;
import net.mihome.app.api.ApiClient;
import net.mihome.app.bean.URLs;
import net.mihome.app.bean.User;
import net.mihome.app.bean.net.ResponsePojo;
import net.mihome.app.common.UIHelper;
import net.mihome.app.common.UpdateManager;
import net.mihome.app.utils.MiAsyncHttpResponseHandler;

import org.apache.http.Header;

import java.util.List;
import java.util.Map;
import java.util.UUID;

import greendroid.widget.MyQuickAction;
import greendroid.widget.QuickActionGrid;
import greendroid.widget.QuickActionWidget;
import greendroid.widget.QuickActionWidget.OnQuickActionClickListener;

public class MainPager extends BaseFragmentActivity {

    // 账号在别处登录
    public boolean isConflict = false;
    protected static final String TAG = "MainPager";
	public static final int QUICKACTION_LOGIN_OR_LOGOUT = 0;
	public static final int QUICKACTION_USERINFO = 1;
	public static final int QUICKACTION_SOFTWARE = 2;
	public static final int QUICKACTION_SEARCH = 3;
	public static final int QUICKACTION_SETTING = 2;
	public static final int QUICKACTION_EXIT = 3;
	private DoubleClickExitHelper mDoubleClickExitHelper;
	private ImageView fbSetting;
	//
	private ViewPager viewPager;
	private ViewPager mifuwuViewPager;
    private ImageView mifuwuImageImg4;
	//
	private RadioButton mihomeButton;
	private RadioButton mifuwuButton;
	//底部按钮
	private View bottomMifuwuView;
	private View bottomMihomeView;	
	//顶部标签按钮
	private View tabButtonDazibaoView;
    private View tabButtonRedianxinwenView;
    private View tabButtonLinliquanView;
    private View tabButtonMineView;
	private QuickActionWidget mGrid;// 快捷栏控件
    private MyFragmentAdapter myFragmentAdapter;
    private MifuwuFragmentAdapter mifuwuFragmentAdapter;
    //
    private View frameBtnMifuwu;  //米服务中的顶部标签
    private View frameBtnMine;  //米服务中的顶部标签
	//顶部标签栏view
	private View tabDazibaoView;
    private View tabLinliquanView;
	private View tabRedianxinwenView;
	private TextView mifuwuCommunityName;
//	private LoadingDialog loadingDialog;
	private AppContext appContext;// 全局Context
    private NewMessageBroadcastReceiver msgReceiver;
    private UserDao userDao;
    //米服务相关操作
//    private ImageView mifuwuTopAdvertIv;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
        if (savedInstanceState != null && savedInstanceState.getBoolean("isConflict", false)) {
            // 防止被T后，没点确定按钮然后按了home键，长期在后台又进app导致的crash
            // 三个fragment里加的判断同理
            finish();
            startActivity(new Intent(this, com.easemob.chatuidemo.activity.LoginActivity.class));
            return;
        }
		mDoubleClickExitHelper = new DoubleClickExitHelper(this);
		appContext = (AppContext) getApplication();
		setContentView(R.layout.main_pager);
        frameBtnMifuwu=findViewById(R.id.frame_btn_mifuwu);
        frameBtnMine=findViewById(R.id.frame_btn_mifuwu_mine);
		viewPager=(ViewPager) findViewById(R.id.mihome_viewpager);
		mifuwuViewPager=(ViewPager) findViewById(R.id.mifuwu_viewpager);
        myFragmentAdapter=new MyFragmentAdapter(getSupportFragmentManager());
        mifuwuFragmentAdapter=new MifuwuFragmentAdapter(getSupportFragmentManager());
        viewPager.setAdapter(myFragmentAdapter);
        viewPager.setCurrentItem(0);
        viewPager.setOffscreenPageLimit(4);// 设置缓存页面，当前页面的相邻N各页面都会被缓存
        viewPager.setOnPageChangeListener(new MyOnPageChangeListener());

        mifuwuImageImg4= (ImageView) findViewById(R.id.mifuwu_img_btn4);

        mifuwuViewPager.setAdapter(mifuwuFragmentAdapter);
        mifuwuViewPager.setCurrentItem(0);
        mifuwuViewPager.setOffscreenPageLimit(2);// 设置缓存页面，当前页面的相邻N各页面都会被缓存
        mifuwuViewPager.setOnPageChangeListener(new miFuwuOnPageChangeListener());
//        mifuwuViewPager.setOnPageChangeListener(new MyOnPageChangeListener());
        //
//        mifuwuTopAdvertIv= (ImageView) findViewById(R.id.mifuwu_top_advert_img);
		this.initQuickActionGrid(); //初始化menu菜单
		//
		LayoutInflater mInflater = getLayoutInflater();
//		//
		mihomeButton = (RadioButton) findViewById(R.id.main_footbar_news);
		mifuwuButton = (RadioButton) findViewById(R.id.main_footbar_question);
		bottomMifuwuView=findViewById(R.id.mifuwu);
		bottomMihomeView=findViewById(R.id.mihome);

        mifuwuCommunityName= (TextView) bottomMifuwuView.findViewById(R.id.frame_btn_community_name);
        User user=appContext.getLoginInfo();
        if(user!=null&&user.getCommunityName()!=null&&!"".equals(user.getCommunityName().trim())){
            mifuwuCommunityName.setText(user.getCommunityName());
        }
//		//顶部标签按钮
		tabButtonDazibaoView =findViewById(R.id.frame_btn_mihome_dazibao);
		tabButtonRedianxinwenView= findViewById(R.id.frame_btn_mihome_redianxinwen);
		tabButtonLinliquanView=findViewById(R.id.frame_btn_mihome_linliquan);
        tabButtonMineView=findViewById(R.id.frame_btn_mihome_mine);
//		//初始化底部按钮
        mihomeButton.setChecked(true);
		mihomeButton.setOnClickListener(buttOnClickListener);
		mifuwuButton.setOnClickListener(buttOnClickListener);
		
		tabButtonLinliquanView.setOnClickListener(topTabOnClickListener);
		tabButtonRedianxinwenView.setOnClickListener(topTabOnClickListener);
		tabButtonDazibaoView.setOnClickListener(topTabOnClickListener);
		tabButtonMineView.setOnClickListener(topTabOnClickListener);
        frameBtnMifuwu.setOnClickListener(topTabOnClickListener);
        frameBtnMine.setOnClickListener(topTabOnClickListener);
		//初始化菜单
		fbSetting = (ImageView) findViewById(R.id.main_footbar_setting);
		fbSetting.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				// 展示快捷栏&判断是否登录&是否加载文章图片
				UIHelper.showSettingLoginOrLogout(MainPager.this,
						mGrid.getQuickAction(0));
				mGrid.show(v);
			}
		});
//		//默认初始化大字报页面，并将大字报按钮置为不可用状态
//        tabButtonDazibaoView.setEnabled(false);
        ((ImageView)tabButtonDazibaoView.findViewById(R.id.img_btn1)).setEnabled(false);
        ((ImageView)tabButtonLinliquanView.findViewById(R.id.img_btn2)).setEnabled(true);
        ((ImageView)tabButtonRedianxinwenView.findViewById(R.id.img_btn3)).setEnabled(true);
        ///环信列表

        inviteMessgeDao = new InviteMessgeDao(this);
        userDao = new UserDao(this);
        // 注册一个接收消息的BroadcastReceiver
        msgReceiver = new NewMessageBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter(EMChatManager.getInstance().getNewMessageBroadcastAction());
        intentFilter.setPriority(3);
        registerReceiver(msgReceiver, intentFilter);

        // 注册一个ack回执消息的BroadcastReceiver
        IntentFilter ackMessageIntentFilter = new IntentFilter(EMChatManager.getInstance().getAckMessageBroadcastAction());
        ackMessageIntentFilter.setPriority(3);
        registerReceiver(ackMessageReceiver, ackMessageIntentFilter);

        //注册一个透传消息的BroadcastReceiver
        IntentFilter cmdMessageIntentFilter = new IntentFilter(EMChatManager.getInstance().getCmdMessageBroadcastAction());
        cmdMessageIntentFilter.setPriority(3);
        registerReceiver(cmdMessageReceiver, cmdMessageIntentFilter);



        // 注册一个离线消息的BroadcastReceiver
        // IntentFilter offlineMessageIntentFilter = new
        // IntentFilter(EMChatManager.getInstance()
        // .getOfflineMessageBroadcastAction());
        // registerReceiver(offlineMessageReceiver, offlineMessageIntentFilter);

        // setContactListener监听联系人的变化等
        EMContactManager.getInstance().setContactListener(new MyContactListener());
        // 注册一个监听连接状态的listener
        EMChatManager.getInstance().addConnectionListener(new MyConnectionListener());
        // 注册圈子相关的listener
        EMGroupManager.getInstance().addGroupChangeListener(new MyGroupChangeListener());
        // 通知sdk，UI 已经初始化完毕，注册了相应的receiver和listener, 可以接受broadcast了
        EMChat.getInstance().setAppInited();
        // 检查新版本
//        if (appContext.isCheckUp()) {
            UpdateManager.getUpdateManager().checkAppUpdate(this, false);
//        }
        this.checkBackGround();
        //加载米服务顶部广告图片
//        ImageLoader.getInstance().displayImage("",mifuwuTopAdvertIv);
	}
	//初始化地步按钮
	View.OnClickListener buttOnClickListener=new View.OnClickListener() {
		@Override
		public void onClick(View view) {
			if(view==mihomeButton){
				bottomMihomeView.setVisibility(View.VISIBLE);
				mihomeButton.setChecked(true);
				bottomMifuwuView.setVisibility(View.GONE);
				mifuwuButton.setChecked(false);
			}else{
				bottomMihomeView.setVisibility(View.GONE);
				mihomeButton.setChecked(false);
				bottomMifuwuView.setVisibility(View.VISIBLE);
				mifuwuButton.setChecked(true);
			}
		}
	};
	/**
	 * 顶部buton的事件
	 * 
	 */
	View.OnClickListener topTabOnClickListener=new View.OnClickListener() {
		@Override
		public void onClick(View view) {
			switch (view.getId()) {
			case R.id.frame_btn_mihome_dazibao:
				viewPager.setCurrentItem(0);
                ((ImageView)tabButtonDazibaoView.findViewById(R.id.img_btn1)).setEnabled(false);
                ((ImageView)tabButtonLinliquanView.findViewById(R.id.img_btn2)).setEnabled(true);
                ((ImageView)tabButtonRedianxinwenView.findViewById(R.id.img_btn3)).setEnabled(true);
                ((ImageView)tabButtonMineView.findViewById(R.id.img_btn4)).setEnabled(true);
				break;
			case R.id.frame_btn_mihome_linliquan:
				viewPager.setCurrentItem(1);
                ((ImageView)tabButtonDazibaoView.findViewById(R.id.img_btn1)).setEnabled(true);
                ((ImageView)tabButtonLinliquanView.findViewById(R.id.img_btn2)).setEnabled(false);
                ((ImageView)tabButtonRedianxinwenView.findViewById(R.id.img_btn3)).setEnabled(true);
                ((ImageView)tabButtonMineView.findViewById(R.id.img_btn4)).setEnabled(true);
				break;
			case R.id.frame_btn_mihome_redianxinwen:
				viewPager.setCurrentItem(2);
                ((ImageView)tabButtonDazibaoView.findViewById(R.id.img_btn1)).setEnabled(true);
                ((ImageView)tabButtonLinliquanView.findViewById(R.id.img_btn2)).setEnabled(true);
                ((ImageView)tabButtonRedianxinwenView.findViewById(R.id.img_btn3)).setEnabled(false);
                ((ImageView)tabButtonMineView.findViewById(R.id.img_btn4)).setEnabled(true);
				break;
            case R.id.frame_btn_mihome_mine:
                viewPager.setCurrentItem(3);
                ((ImageView)tabButtonDazibaoView.findViewById(R.id.img_btn1)).setEnabled(true);
                ((ImageView)tabButtonLinliquanView.findViewById(R.id.img_btn2)).setEnabled(true);
                ((ImageView)tabButtonRedianxinwenView.findViewById(R.id.img_btn3)).setEnabled(true);
                ((ImageView)tabButtonMineView.findViewById(R.id.img_btn4)).setEnabled(false);
                break;
            case R.id.frame_btn_mifuwu:
                mifuwuCommunityName.setTextColor(getResources().getColor(R.color.top_bar_normal_bg));
                mifuwuImageImg4.setEnabled(true);
                mifuwuViewPager.setCurrentItem(0);
                break;
            case  R.id.frame_btn_mifuwu_mine:
                mifuwuCommunityName.setTextColor(getResources().getColor(R.color.black));
                mifuwuImageImg4.setEnabled(false);
                mifuwuViewPager.setCurrentItem(1);
                break;
			default:
				break;
			}
		}
	};

    /**
     * 页卡切换监听
*/
    public class MyOnPageChangeListener implements OnPageChangeListener {

        @Override
        public void onPageSelected(int arg0) {
        	switch (arg0) {
			case 0:
                ((ImageView)tabButtonDazibaoView.findViewById(R.id.img_btn1)).setEnabled(false);
                ((ImageView)tabButtonLinliquanView.findViewById(R.id.img_btn2)).setEnabled(true);
                ((ImageView)tabButtonRedianxinwenView.findViewById(R.id.img_btn3)).setEnabled(true);
                ((ImageView)tabButtonMineView.findViewById(R.id.img_btn4)).setEnabled(true);
				break;
			case 1:
                ((ImageView)tabButtonDazibaoView.findViewById(R.id.img_btn1)).setEnabled(true);
                ((ImageView)tabButtonLinliquanView.findViewById(R.id.img_btn2)).setEnabled(false);
                ((ImageView)tabButtonRedianxinwenView.findViewById(R.id.img_btn3)).setEnabled(true);
                ((ImageView)tabButtonMineView.findViewById(R.id.img_btn4)).setEnabled(true);
				break;
			case 2:
                ((ImageView)tabButtonDazibaoView.findViewById(R.id.img_btn1)).setEnabled(true);
                ((ImageView)tabButtonLinliquanView.findViewById(R.id.img_btn2)).setEnabled(true);
                ((ImageView)tabButtonRedianxinwenView.findViewById(R.id.img_btn3)).setEnabled(false);
                ((ImageView)tabButtonMineView.findViewById(R.id.img_btn4)).setEnabled(true);
				break;
            case 3:
                ((ImageView)tabButtonDazibaoView.findViewById(R.id.img_btn1)).setEnabled(true);
                ((ImageView)tabButtonLinliquanView.findViewById(R.id.img_btn2)).setEnabled(true);
                ((ImageView)tabButtonRedianxinwenView.findViewById(R.id.img_btn3)).setEnabled(true);
                ((ImageView)tabButtonMineView.findViewById(R.id.img_btn4)).setEnabled(false);
                break;
			default:
				break;
			}
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
        }
    }
    /**
     * 页卡切换监听
     */
    public class miFuwuOnPageChangeListener implements OnPageChangeListener {

        @Override
        public void onPageSelected(int arg0) {
            switch (arg0) {
                case 0:
                    mifuwuCommunityName.setTextColor(getResources().getColor(R.color.top_bar_normal_bg));
                    mifuwuImageImg4.setEnabled(true);
                    break;
                case 1:
                    mifuwuCommunityName.setTextColor(getResources().getColor(R.color.black));
                    mifuwuImageImg4.setEnabled(false);
                    break;
                default:
                    break;
            }
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
        }
    }
    /**
	 * 初始化快捷栏
	 */
	private void initQuickActionGrid() {
		mGrid = new QuickActionGrid(this);
		mGrid.addQuickAction(new MyQuickAction(this, R.drawable.ic_menu_login,
				R.string.main_menu_login));
		mGrid.addQuickAction(new MyQuickAction(this, R.drawable.ic_menu_myinfo,
				R.string.main_menu_myinfo));
//		mGrid.addQuickAction(new MyQuickAction(this,
//				R.drawable.ic_menu_software, R.string.main_menu_software));
//		mGrid.addQuickAction(new MyQuickAction(this, R.drawable.ic_menu_sweep,
//				R.string.main_menu_sweep));
		mGrid.addQuickAction(new MyQuickAction(this,
				R.drawable.ic_menu_setting, R.string.main_menu_setting));
		mGrid.addQuickAction(new MyQuickAction(this, R.drawable.ic_menu_exit,
				R.string.main_menu_exit));

		mGrid.setOnQuickActionClickListener(mActionListener);
	}
	/**
	 * 快捷栏item点击事件
	 */
	private OnQuickActionClickListener mActionListener = new OnQuickActionClickListener() {
		public void onQuickActionClicked(QuickActionWidget widget, int position) {
			switch (position) {
			case QUICKACTION_LOGIN_OR_LOGOUT:// 用户登录-注销
				UIHelper.loginOrLogout(MainPager.this);
				break;
			case QUICKACTION_USERINFO:// 我的资料
				UIHelper.showUserInfo(MainPager.this);
				break;
			case QUICKACTION_SETTING:// 设置
				UIHelper.showSetting(MainPager.this);
				break;
			case QUICKACTION_EXIT:// 退出
                EMChatManager.getInstance().logout();//此方法为同步方法
				AppManager.getAppManager().finishActivity(MainPager.this);
				break;
			}
		}
	};
	/**
	 * 创建menu TODO 停用原生菜单
	 */
	public boolean onCreateOptionsMenu(Menu menu) {
		return false;
	}

	/**
	 * 菜单被显示之前的事件
	 */
	public boolean onPrepareOptionsMenu(Menu menu) {
		UIHelper.showMenuLoginOrLogout(this, menu);
		return true;
	}

	/**
	 * 处理menu的事件
	 */
	public boolean onOptionsItemSelected(MenuItem item) {
		int item_id = item.getItemId();
		switch (item_id) {
		case R.id.main_menu_user:
			UIHelper.loginOrLogout(this);
			break;
		case R.id.main_menu_about:
			UIHelper.showAbout(this);
			break;
		case R.id.main_menu_setting:
			UIHelper.showSetting(this);
			break;
		case R.id.main_menu_exit:
			UIHelper.Exit(this);
			break;
		}
		return true;
	}
	/**
	 * 监听返回--是否退出程序
	 */
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		boolean flag = true;
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			// 是否退出应用
			return mDoubleClickExitHelper.onKeyDown(keyCode, event);
		} else if (keyCode == KeyEvent.KEYCODE_MENU) {
			// 展示快捷栏&判断是否登录
			UIHelper.showSettingLoginOrLogout(MainPager.this,
					mGrid.getQuickAction(0));
			mGrid.show(fbSetting, true);
		} else if (keyCode == KeyEvent.KEYCODE_SEARCH) {
			// 展示搜索页
			UIHelper.showSearch(MainPager.this);
		} else {
			flag = super.onKeyDown(keyCode, event);
		}
		return flag;
	}
	private void checkBackGround() {
		if (!appContext.isNetworkConnected()) {
			return;
		}
		// 启动线程去检查服务器接口是否需要下载新的欢迎界面背景图片到手机
		new Thread(){
			public void run() {
				// 将图片下载下来
				try {
					ApiClient.checkBackGround(appContext);
				} catch (AppException e) {
				}
			}
		}.start();
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
        if(viewPager.getCurrentItem()==0){
            myFragmentAdapter.getItem(0).onActivityResult(requestCode,  resultCode, data);
        }
	}
    /**
     * 新消息广播接收者
     *
     *
     */
    private class NewMessageBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            // 主页面收到消息后，主要为了提示未读，实际消息内容需要到chat页面查看
            try {

                String from = intent.getStringExtra("from");
                // 消息id
                String msgId = intent.getStringExtra("msgid");
                EMMessage message = EMChatManager.getInstance().getMessage(msgId);
                // 2014-10-22 修复在某些机器上，在聊天页面对方发消息过来时不立即显示内容的bug
                if (com.easemob.chatuidemo.activity.ChatActivity.activityInstance != null) {
                    if (message.getChatType() == EMMessage.ChatType.GroupChat) {
                        if (message.getTo().equals(com.easemob.chatuidemo.activity.ChatActivity.activityInstance.getToChatUsername()))
                            return;
                    } else {
                        if (from.equals(com.easemob.chatuidemo.activity.ChatActivity.activityInstance.getToChatUsername()))
                            return;
                    }
                }

                // 注销广播接收者，否则在ChatActivity中会收到这个广播
                abortBroadcast();

                notifyNewMessage(message);

//            // 刷新bottom bar消息未读数
//            updateUnreadLabel();
                // 当前页面如果为聊天历史页面，刷新此页面
                if (myFragmentAdapter.getItem(1) != null) {
                    ((LinliquanFragment)myFragmentAdapter.getItem(1)).refresh();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 消息回执BroadcastReceiver
     */
    private BroadcastReceiver ackMessageReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            abortBroadcast();

            String msgid = intent.getStringExtra("msgid");
            String from = intent.getStringExtra("from");

            EMConversation conversation = EMChatManager.getInstance().getConversation(from);
            if (conversation != null) {
                // 把message设为已读
                EMMessage msg = conversation.getMessage(msgid);

                if (msg != null) {

                    // 2014-11-5 修复在某些机器上，在聊天页面对方发送已读回执时不立即显示已读的bug
                    if (com.easemob.chatuidemo.activity.ChatActivity.activityInstance != null) {
                        if (msg.getChatType() == EMMessage.ChatType.Chat) {
                            if (from.equals(com.easemob.chatuidemo.activity.ChatActivity.activityInstance.getToChatUsername()))
                                return;
                        }
                    }

                    msg.isAcked = true;
                }
            }

        }
    };



    /**
     * 透传消息BroadcastReceiver
     */
    private BroadcastReceiver cmdMessageReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            abortBroadcast();
            EMLog.d(TAG, "收到透传消息");
            //获取cmd message对象
            String msgId = intent.getStringExtra("msgid");
            EMMessage message = intent.getParcelableExtra("message");
            //获取消息body
            CmdMessageBody cmdMsgBody = (CmdMessageBody) message.getBody();
            String action = cmdMsgBody.action;//获取自定义action

            //获取扩展属性 此处省略
//			message.getStringAttribute("");
            EMLog.d(TAG, String.format("透传消息：action:%s,message:%s", action,message.toString()));
            Toast.makeText(MainPager.this, "收到透传：action：" + action, Toast.LENGTH_SHORT).show();
        }
    };

    /**
     * 离线消息BroadcastReceiver sdk 登录后，服务器会推送离线消息到client，这个receiver，是通知UI
     * 有哪些人发来了离线消息 UI 可以做相应的操作，比如下载用户信息
     */
    // private BroadcastReceiver offlineMessageReceiver = new
    // BroadcastReceiver() {
    //
    // @Override
    // public void onReceive(Context context, Intent intent) {
    // String[] users = intent.getStringArrayExtra("fromuser");
    // String[] groups = intent.getStringArrayExtra("fromgroup");
    // if (users != null) {
    // for (String user : users) {
    // System.out.println("收到user离线消息：" + user);
    // }
    // }
    // if (groups != null) {
    // for (String group : groups) {
    // System.out.println("收到group离线消息：" + group);
    // }
    // }
    // }
    // };

    private InviteMessgeDao inviteMessgeDao;
    /***
     * 好友变化listener
     *
     */
    private class MyContactListener implements EMContactListener {

        @Override
        public void onContactAdded(List<String> usernameList) {
            // 保存增加的联系人
            final Map<String, User> localUsers = AppContext.getInstance().getContactList();
            for (final String username : usernameList) {
                RequestParams requestParams=new RequestParams();
                requestParams.add("open_id",username);
                //给服务器新加一个接口，通过一个openid获取用户的详细信息
                AppContext.SYNC_HTTP_CLIENT.get(MainPager.this, URLs.MIHOME_USER_CHAT_GET_USER_BY_OPENID,requestParams,new MiAsyncHttpResponseHandler<Map>() {
                    @Override
                    public void onSuccess(int arg0, Header[] arg1, ResponsePojo<Map> responsePojo) {
                        User user2 = User.parse(responsePojo.getData());
                        String showName = user2.getName();
                        if (user2.getRealName() != null && !"".equals(user2.getRealName().trim())) {
                            showName = user2.getRealName();
                        }
                        User user = setUserHead(username);
                        user2.setHeader(user.getHeader());
                        // 添加好友时可能会回调added方法两次bb
                        if (!localUsers.containsKey(username)) {
                            userDao.saveContact(user2);
                        }
                        //添加到内存中的好友列表中
                        localUsers.put(username,user2);
                    }
                    @Override
                    public void onFailure(int arg0, Header[] arg1, Throwable arg3) {
                        Toast.makeText(MainPager.this,"获取好友信息失败",Toast.LENGTH_SHORT).show();
                    }
                });
            }

        }

        @Override
        public void onContactDeleted(final List<String> usernameList) {
            // 被删除
            Map<String, User> localUsers = AppContext.getInstance().getContactList();
            for (String username : usernameList) {
                localUsers.remove(username);
                userDao.deleteContact(username);
                inviteMessgeDao.deleteMessage(username);
            }
            runOnUiThread(new Runnable() {
                public void run() {
                    // 如果正在与此用户的聊天页面
                    if (com.easemob.chatuidemo.activity.ChatActivity.activityInstance != null && usernameList.contains(com.easemob.chatuidemo.activity.ChatActivity.activityInstance.getToChatUsername())) {
                        Toast.makeText(MainPager.this, com.easemob.chatuidemo.activity.ChatActivity.activityInstance.getToChatUsername() + "已把你从他好友列表里移除", Toast.LENGTH_LONG).show();
                        ChatActivity.activityInstance.finish();
                    }
                }
            });

        }

        @Override
        public void onContactInvited(String username, String reason) {
            // 接到邀请的消息，如果不处理(同意或拒绝)，掉线后，服务器会自动再发过来，所以客户端不需要重复提醒
            List<InviteMessage> msgs = inviteMessgeDao.getMessagesList();

            for (InviteMessage inviteMessage : msgs) {
                if (inviteMessage.getGroupId() == null && inviteMessage.getFrom().equals(username)) {
                    inviteMessgeDao.deleteMessage(username);
                }
            }
            // 自己封装的javabean
            InviteMessage msg = new InviteMessage();
            msg.setFrom(username);
            msg.setTime(System.currentTimeMillis());
            msg.setReason(reason);
            Log.d(TAG, username + "请求加你为好友,reason: " + reason);
            // 设置相应status
            msg.setStatus(InviteMessage.InviteMesageStatus.BEINVITEED);
            notifyNewIviteMessage(msg);

        }

        @Override
        public void onContactAgreed(String username) {
            List<InviteMessage> msgs = inviteMessgeDao.getMessagesList();
            for (InviteMessage inviteMessage : msgs) {
                if (inviteMessage.getFrom().equals(username)) {
                    return;
                }
            }
            // 自己封装的javabean
            InviteMessage msg = new InviteMessage();
            msg.setFrom(username);
            msg.setTime(System.currentTimeMillis());
            Log.d(TAG, username + "同意了你的好友请求");
            msg.setStatus(InviteMessage.InviteMesageStatus.BEAGREED);
            notifyNewIviteMessage(msg);

        }

        @Override
        public void onContactRefused(String username) {
            // 参考同意，被邀请实现此功能,demo未实现
            Log.d(username, username + "拒绝了你的好友请求");
        }

    }

    /**
     * MyGroupChangeListener
     */
    private class MyGroupChangeListener implements GroupChangeListener {

        @Override
        public void onInvitationReceived(String groupId, String groupName, String inviter, String reason) {
            boolean hasGroup = false;
            for (EMGroup group : EMGroupManager.getInstance().getAllGroups()) {
                if (group.getGroupId().equals(groupId)) {
                    hasGroup = true;
                    break;
                }
            }
            if (!hasGroup)
                return;

            // 被邀请
            EMMessage msg = EMMessage.createReceiveMessage(EMMessage.Type.TXT);
            msg.setChatType(EMMessage.ChatType.GroupChat);
            msg.setFrom(inviter);
            msg.setTo(groupId);
            msg.setMsgId(UUID.randomUUID().toString());
            msg.addBody(new TextMessageBody(inviter + "邀请你加入了圈子"));
            // 保存邀请消息
            EMChatManager.getInstance().saveMessage(msg);
            // 提醒新消息
            EMNotifier.getInstance(getApplicationContext()).notifyOnNewMsg();

            runOnUiThread(new Runnable() {
                public void run() {
//                    updateUnreadLabel();
//                    // 刷新ui
//                    if (currentTabIndex == 0)
//                        chatHistoryFragment.refresh();
                    if (CommonUtils.getTopActivity(MainPager.this).equals(GroupsActivity.class.getName())) {
                        GroupsActivity.instance.onResume();
                    }
                }
            });

        }

        @Override
        public void onInvitationAccpted(String groupId, String inviter, String reason) {

        }

        @Override
        public void onInvitationDeclined(String groupId, String invitee, String reason) {

        }

        @Override
        public void onUserRemoved(String groupId, String groupName) {
            // 提示用户被T了，demo省略此步骤
            // 刷新ui
            runOnUiThread(new Runnable() {
                public void run() {
                    try {
//                        updateUnreadLabel();
//                        if (currentTabIndex == 0)
//                            chatHistoryFragment.refresh();
                        if (CommonUtils.getTopActivity(MainPager.this).equals(GroupsActivity.class.getName())) {
                            GroupsActivity.instance.onResume();
                        }
                    } catch (Exception e) {
                        EMLog.e(TAG, "refresh exception " + e.getMessage());
                    }

                }
            });
        }

        @Override
        public void onGroupDestroy(String groupId, String groupName) {
            // 群被解散
            // 提示用户群被解散,demo省略
            // 刷新ui
            runOnUiThread(new Runnable() {
                public void run() {
//                    updateUnreadLabel();
//                    if (currentTabIndex == 0)
//                        chatHistoryFragment.refresh();
                    if (CommonUtils.getTopActivity(MainPager.this).equals(GroupsActivity.class.getName())) {
                        GroupsActivity.instance.onResume();
                    }
                }
            });

        }

        @Override
        public void onApplicationReceived(String groupId, String groupName, String applyer, String reason) {
            // 用户申请加入圈子
            InviteMessage msg = new InviteMessage();
            msg.setFrom(applyer);
            msg.setTime(System.currentTimeMillis());
            msg.setGroupId(groupId);
            msg.setGroupName(groupName);
            msg.setReason(reason);
            Log.d(TAG, applyer + " 申请加入圈子：" + groupName);
            msg.setStatus(InviteMessage.InviteMesageStatus.BEAPPLYED);
            notifyNewIviteMessage(msg);
        }

        @Override
        public void onApplicationAccept(String groupId, String groupName, String accepter) {
            // 加群申请被同意
            EMMessage msg = EMMessage.createReceiveMessage(EMMessage.Type.TXT);
            msg.setChatType(EMMessage.ChatType.GroupChat);
            msg.setFrom(accepter);
            msg.setTo(groupId);
            msg.setMsgId(UUID.randomUUID().toString());
            msg.addBody(new TextMessageBody(accepter + "同意了你的圈子申请"));
            // 保存同意消息
            EMChatManager.getInstance().saveMessage(msg);
            // 提醒新消息
            EMNotifier.getInstance(getApplicationContext()).notifyOnNewMsg();

            runOnUiThread(new Runnable() {
                public void run() {
//                    updateUnreadLabel();
//                    // 刷新ui
//                    if (currentTabIndex == 0)
//                        chatHistoryFragment.refresh();
                    if (CommonUtils.getTopActivity(MainPager.this).equals(GroupsActivity.class.getName())) {
                        GroupsActivity.instance.onResume();
                    }
                }
            });
        }

        @Override
        public void onApplicationDeclined(String groupId, String groupName, String decliner, String reason) {
            // 加群申请被拒绝，demo未实现
        }

    }
    /**
     * set head
     *
     * @param username
     * @return
     */
    User setUserHead(String username) {
        User user = new User();
        user.setUsername(username);
        String headerName = null;
        if (!TextUtils.isEmpty(user.getNick())) {
            headerName = user.getNick();
        } else {
            headerName = user.getUsername();
        }
        if (username.equals(Constant.NEW_FRIENDS_USERNAME)) {
            user.setHeader("");
        } else if (Character.isDigit(headerName.charAt(0))) {
            user.setHeader("#");
        } else {
            user.setHeader(HanziToPinyin.getInstance().get(headerName.substring(0, 1)).get(0).target.substring(0, 1).toUpperCase());
            char header = user.getHeader().toLowerCase().charAt(0);
            if (header < 'a' || header > 'z') {
                user.setHeader("#");
            }
        }
        return user;
    }
    /**
     * 保存提示新消息
     *
     * @param msg
     */
    private void notifyNewIviteMessage(InviteMessage msg) {
        saveInviteMsg(msg);
        // 提示有新消息
        EMNotifier.getInstance(getApplicationContext()).notifyOnNewMsg();
//
//        // 刷新bottom bar消息未读数
//        updateUnreadAddressLable();
//        // 刷新好友页面ui
//        if (currentTabIndex == 1)
//            contactListFragment.refresh();
    }

    /**
     * 保存邀请等msg
     *
     * @param msg
     */
    private void saveInviteMsg(final InviteMessage msg) {
        // 保存msg
        RequestParams requestParams=new RequestParams();
        requestParams.add("open_id",msg.getFrom());
        //给服务器新加一个接口，通过一个openid获取用户的详细信息
        AppContext.SYNC_HTTP_CLIENT.get(this, URLs.MIHOME_USER_CHAT_GET_USER_BY_OPENID,requestParams,new MiAsyncHttpResponseHandler<Map>() {
            @Override
            public void onSuccess(int arg0, Header[] arg1, ResponsePojo<Map> responsePojo) {
                User user2=User.parse(responsePojo.getData());
                String showName=user2.getName();
                if(user2.getRealName()!=null&&!"".equals(user2.getRealName().trim())){
                    showName=user2.getRealName();
                }
                msg.setFromName(showName);
                // 未读数加1
                User user = AppContext.getInstance().getContactList().get(Constant.NEW_FRIENDS_USERNAME);
                if (user.getUnreadMsgCount() == 0){
                    user.setUnreadMsgCount(user.getUnreadMsgCount() + 1);
                    //刷新通讯录列表，使其显示未读新邻居
                    ((ContactlistFragment)myFragmentAdapter.getItem(1)).refresh();
                }
                inviteMessgeDao.saveMessage(msg);
            }

            @Override
            public void onFailure(int arg0, Header[] arg1, Throwable arg3) {
                msg.setFromName(msg.getFrom());
                inviteMessgeDao.saveMessage(msg);
                // 未读数加1
                User user = AppContext.getInstance().getContactList().get(Constant.NEW_FRIENDS_USERNAME);
                if (user.getUnreadMsgCount() == 0)
                    user.setUnreadMsgCount(user.getUnreadMsgCount() + 1);
            }
        });
    }
    /**
     * 连接监听listener
     *
     */
    private class MyConnectionListener implements EMConnectionListener {

        @Override
        public void onConnected() {
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    LinliquanFragment linliquanFragment = (LinliquanFragment) myFragmentAdapter.getItem(1);
                    if(linliquanFragment!=null){
                        linliquanFragment.connected();
                    }
//                    chatHistoryFragment.errorItem.setVisibility(View.GONE);
                }

            });
        }

        @Override
        public void onDisconnected(final int error) {
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    if (error == EMError.CONNECTION_CONFLICT) {
                        // 显示帐号在其他设备登陆dialog
                        if(MainPager.this!=null&&!MainPager.this.isDestroyed())
                        {
                            UIHelper.showAlertDialog(MainPager.this, "提示", "账号在其他设备登录", onLogoutListener);
                        }else{
                            UIHelper.showAlertDialog(getParent(), "提示", "账号在其他设备登录", onLogoutListener);
                        }
                    } else {

                        LinliquanFragment linliquanFragment = (LinliquanFragment) myFragmentAdapter.getItem(1);
                        if(linliquanFragment!=null){
                            linliquanFragment.unconnect();
                        }
//                        if (NetUtils.hasNetwork(MainPager.this)){
////                            UIHelper.showAlertDialog(MainPager.this,"提示","连接不到聊天服务器",onLogoutListener);
//                              showDialogOfterDisconnect();
//                        }
//                        else{
////                            UIHelper.showAlertDialog(MainPager.this,"提示","当前网络不可用，请检查网络设置",onLogoutListener);
//                            showDialogOfterDisconnect();
//                        }
                    }
                }

            });
        }
    }
    private DialogInterface.OnClickListener onLogoutListener=new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            appContext.cleanLoginInfo();
            appContext.cleanCookie();
            UIHelper.loginOrLogout(MainPager.this);
        }
    };
    @Override
    protected void onDestroy() {
        unregisterReceiver(msgReceiver);
        super.onDestroy();
    }
//    /**
//     * 断网之后的弹窗提示
//     * */
//    public void showDialogOfterDisconnect(){
//
//        Toast.makeText(MainPager.this,"与服务器断开了",Toast.LENGTH_SHORT).show();
////        AlertDialog.Builder builder = new AlertDialog.Builder(this);
//        builder.setTitle("提示:");
//        builder.setMessage("您与米宅的网络连接中断,请检查网络连接之后点击重新连接，或者点击退出直接退出米宅.");
//        builder.setPositiveButton("退出", onLogoutListener);
//        builder.setNegativeButton("重新连接",new DialogInterface.OnClickListener() {
//            @Override
//            public void onClick(DialogInterface dialogInterface, int i) {
////                EMChatManager.getInstance().removeConnectionListener(new EMConnectionListener() {
////                    @Override
////                    public void onConnected() {
////                        Toast.makeText(MainPager.this,"重连成功",Toast.LENGTH_LONG).show();
////                    }
////
////                    @Override
////                    public void onDisconnected(int i) {
////                        Toast.makeText(MainPager.this,"重连成功",Toast.LENGTH_LONG).show();
////                    }
////                });
//            }
//        });
//        builder.create().show();
//    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

    }
}
